package com.gz.springboot.controller;

import com.gz.springboot.bean.Admin;
import com.gz.springboot.bean.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@Controller
@Slf4j //显示日志
public class AdminController {

    //注意IndexController中也有一个/login，但是他们的method不同即这里是PostMapping，故会自动区分
    @PostMapping("/login")
    public String login(Admin admin, HttpSession session, Model model) {
        if(StringUtils.hasText(admin.getName())&&"666".equals(admin.getPassword())){
            //合法
            //将用户保存到session
            session.setAttribute("admin",admin);
//            session.setMaxInactiveInterval(50); //这里50是s,不是ms
            //不使用请求转发是防止刷新页面重复提交
            return "redirect:/manage.html";
        }else {
            //不合法
            model.addAttribute("msg","账号/用户错误");
            return "adminLogin";
        }
    }

    @GetMapping(value = "manage.html")
    public String mainPage(Model model,HttpSession session) {

        log.info("进入mainPage()");

        ArrayList<User> users = new ArrayList<>();
        users.add(new User(1, "关羽~", "666666", 20, "gy@sohu.com"));
        users.add(new User(2, "张飞", "666666", 30, "zf@sohu.com"));
        users.add(new User(3, "赵云", "666666", 22, "zy@sohu.com"));
        users.add(new User(4, "马超", "666666", 28, "mc@sohu.com"));
        users.add(new User(5, "黄忠", "666666", 50, "hz@sohu.com"));

        //将数据放入到request域
        model.addAttribute("users", users);
        return "manage";

    }

}
